package com.citycloud.ccuap.tc.admin.role;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.citycloud.ccuap.commons.db.LikeMatchMode;
import com.citycloud.ccuap.commons.db.SqlRestrictions;
import com.citycloud.ccuap.commons.sys.entity.SysAct;
import com.citycloud.ccuap.commons.sys.entity.SysRole;
import com.citycloud.ccuap.commons.sys.entity.SysUser;
import com.citycloud.ccuap.commons.sys.repository.SysActRepository;
import com.citycloud.ccuap.commons.sys.repository.SysRoleRepository;
import com.citycloud.ccuap.commons.sys.repository.SysUserRepository;
import com.citycloud.ccuap.framework.mybatis.pagination.PageQuery;
import com.citycloud.ccuap.framework.service.mybatis.MybatisServiceImpl;

/**
 * @author liujw
 * @create 2019-06-28 11:34
 * Description:
 */
@Service
public class RoleApiServiceImpl extends MybatisServiceImpl<SysRoleRepository, SysRole, Long> implements RoleApiService {

    @Autowired
    SysRoleRepository sysRoleRepository;

    @Autowired
    private SysUserRepository sysUserRepository;

    @Autowired
    private SysActRepository sysActRepository;

    @Resource
    @Lazy
    RoleApiMapper roleApiMapper;

    @Override
    public PageQuery<Map<String, Object>> findByNameAndProId(PageQuery<Map<String, Object>> pageQuery, String roleName,
                                                             Long roleId, Long projectId,
                                                             String orderField, String orderTyp, boolean b) {

        String sql = null;
        if(b ==true){
            sql = getPtQuerySql(roleName, roleId, projectId);
        }else{
            sql = getQuerySql(roleName, roleId, projectId);
        }
        if (!StringUtils.isEmpty(orderField)) {
            Sort.Direction direction = Sort.Direction.valueOf(orderTyp);
            sql += SqlRestrictions.order(orderField, direction);
        } else {
            sql += SqlRestrictions.order("role_code", Sort.Direction.ASC);
        }
        PageQuery<Map<String, Object>> selectPage = selectPage(pageQuery, sql, true);

        return selectPage;
    }

    private String getQuerySql(String roleName, Long roleId, Long projectId) {
        String sql = " SELECT * FROM sys_role WHERE 1=1 ";
        if (projectId == null) {
            sql += " AND project_id IS NULL ";
        } else {
            sql += " AND project_id = " + projectId +" and flag = 0";
        }
        if (null != roleId) {
            sql += " AND role_id = " + roleId;
        }
        sql += SqlRestrictions.like("role_name", roleName, LikeMatchMode.BOTHADD);
        return sql;
    }

    private String getPtQuerySql(String roleName, Long roleId, Long projectId) {
        String sql = "SELECT sys_role.*,sys_project.project_name FROM sys_role LEFT JOIN sys_project ON sys_project.project_id =  sys_role.project_id WHERE sys_role.project_id is not null ORDER BY sys_role.created_time desc ";
        sql += SqlRestrictions.like("role_name", roleName, LikeMatchMode.BOTHADD);
        return sql;
    }

    @Override
    public PageQuery<Map<String, Object>> findByNameAndProId(PageQuery<Map<String, Object>> pageQuery, String roleName,
                                                             Long roleId, Long projectId, boolean b) {
        String sql = null;
        if(b ==true){
            sql = getPtQuerySql(roleName, roleId, projectId);
        }else{
            sql = getQuerySql(roleName, roleId, projectId);
        }
        PageQuery<Map<String, Object>> selectPage = selectPage(pageQuery, sql, true);

        return selectPage;
    }

    @Override
    public List<SysRole> findByRoleCode(String roleCode) {
        return sysRoleRepository.findByRoleCode(roleCode);

    }

    @Override
    public void updateRole(SysRole role) {
        Long roleId = role.getRoleId();
        SysRole existRole = repository.findById(roleId).orElse(null);
        Assert.notNull(existRole, "查询角色信息为空！");
        repository.update(role);

        if (!existRole.getRoleName().equals(role.getRoleName())) {
            // 角色名发生变化时 修改绑定该角色的用户表中相关用户的own_roles字段
            List<SysAct> actist = sysActRepository.findByRoleId(roleId);
            for (SysAct sysAct : actist) {
                // 查找用户所有角色
                List<Map<String, Object>> roleNameList = roleApiMapper.findRoleNameByUserId(sysAct.getUserId());
                StringBuilder roleBuilder = new StringBuilder();
                for (Map<String, Object> map : roleNameList) {
                    roleBuilder.append(map.get("role_name")).append(",");
                }
                String roleNames = roleBuilder.toString();
                SysUser sysUser = sysUserRepository.findById(sysAct.getUserId()).orElse(null);
                if (sysUser != null) {
                    sysUser.setOwnRoles(roleNames.length() == 0 ? "" : roleNames.substring(0, roleNames.length() - 1));
                    sysUserRepository.save(sysUser);
                }

            }
        }
    }


}
